def count_neighbours(g, x, y):
    r = len(g)-1
    c = len(g[0])-1
    if 0<x<r:
        if 0<y<c:
            neighbours = (g[x-1][y-1],g[x-1][y],g[x-1][y+1],
                          g[x][y-1],              g[x][y+1],
                          g[x+1][y-1],g[x+1][y],g[x+1][y+1])
        elif y==0:
            neighbours = (g[x-1][y],g[x-1][y+1],
                                      g[x][y+1],
                          g[x+1][y],g[x+1][y+1])
        elif y==c:
            neighbours = (g[x-1][y-1],g[x-1][y],
                          g[x][y-1],
                          g[x+1][y-1],g[x+1][y])

    elif x==0:
        if 0<y<c:
            neighbours=(g[x][y-1],              g[x][y+1],
                        g[x+1][y-1],g[x+1][y],g[x+1][y+1])
        elif y==0:
            neighbours=(            g[x][y+1],
                        g[x+1][y],g[x+1][y+1])
        elif y==c:
            neighbours=(g[x][y-1],
                        g[x+1][y-1],g[x+1][y])
    elif x==r:
        if 0<y<c:
            neighbours = (g[x-1][y-1],g[x-1][y],g[x-1][y+1],
                          g[x][y-1],              g[x][y+1])
        elif y==0:
            neighbours = (g[x-1][y],g[x-1][y+1],
                                    g[x][y+1])
        elif y==c:
            neighbours = (g[x-1][y-1],g[x-1][y],
                          g[x][y-1],            )


    return neighbours.count(1)

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_neighbours(((1, 0, 0, 1, 0),
                             (0, 1, 0, 0, 0),
                             (0, 0, 1, 0, 1),
                             (1, 0, 0, 0, 0),
                             (0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
    assert count_neighbours(((1, 0, 0, 1, 0),
                             (0, 1, 0, 0, 0),
                             (0, 0, 1, 0, 1),
                             (1, 0, 0, 0, 0),
                             (0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
    assert count_neighbours(((1, 1, 1),
                             (1, 1, 1),
                             (1, 1, 1),), 0, 2) == 3, "Dense corner"
    assert count_neighbours(((0, 0, 0),
                             (0, 1, 0),
                             (0, 0, 0),), 1, 1) == 0, "Single"
